package com.yx.udp.util;


import android.util.Log;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.zip.CRC32;

public class Crc32Utils {

    private static final String TAG = "Crc32Utils";

    /**
     * 计算文件的 CRC32 校验值
     * @param filePath 文件路径
     */
    public static byte[] calculateFileCRC32(String filePath) {
        CRC32 crc32 = new CRC32();
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc32.update(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            Log.e(TAG, "calculateFileCRC32 error: " + e.getMessage());
        }
        return longToBytes32(crc32.getValue());
    }

    /**
     * 将32位CRC的long值转换为4字节数组（大端序）
     */
    private static byte[] longToBytes32(long value) {
        return new byte[]{
                (byte) (value & 0xFF),
                (byte) ((value >> 8) & 0xFF),
                (byte) ((value >> 16) & 0xFF),
                (byte) ((value >> 24) & 0xFF)
        };
    }
}
